/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ImportDataFromPhone;

import java.io.*;
import java.util.Date;
/**
 *
 * @author ash
 */
public class OutputWriter {
    

        private static String getFinalName(String name){
        String finalName = name;
        
        File original = new File (name);
        if (original.exists()){
            
            int lastPeriod = name.lastIndexOf('.');
            finalName = name.substring(0,lastPeriod);
            String extension = name.substring(lastPeriod);
            String timestamp = new Long(new Date().getTime()).toString();
            return finalName + "_" + timestamp + extension;
        }
        return finalName;
    }
    
    
   
    static void write(Container<? extends Record> records, String fileName){
            
            String finalFileName = getFinalName(fileName);
        
            try {
                
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalFileName), "UTF-8"));
                
                if (records.size()>0){
                    out.append(records.getHeader());
                    
                    for (int i=0; i<records.size(); i++){
                        out.newLine();
                        out.append(records.get(i).getCSVString());
                    }
                }
                
                out.close();
            
            } catch (IOException ioe){
                System.out.println(ioe.getMessage());
            }

    }

    public static void main(String[] a){
        Container<ProcessedRecord> plist = new Container<>(ProcessedRecord.class);
        plist.add(new ProcessedRecord("1", "2", "3"));
        OutputWriter.write(plist, "file");
        
        Container<CategorizedRecord> clist = new Container<>(CategorizedRecord.class);
        clist.add(new CategorizedRecord(new ProcessedRecord("2", "3", "4"), "food"));
        OutputWriter.write(clist, "file2");
    }

    
}
